package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper contentMapper;




    public void saveOrUpdate(Travel travel) {
        if (travel.getId() == null) {
            //需要设置作者
            Map map = UserContext.getCurrentUser();
            User user = new User();
            user.setId((Long) map.get("id"));
            travel.setAuthor(user);
            travelMapper.insert(travel);
            //保存游记内容
            TravelContent content = travel.getTravelContent();
            //主键关联
            content.setId(travel.getId());
            contentMapper.insert(content);
        } else {

            //需要更新游记内容
            TravelContent travelContent = travel.getTravelContent();
            travelContent.setId(travel.getId());
            contentMapper.updateByPrimaryKey(travelContent);
            travelMapper.updateByPrimaryKey(travel);
        }
    }

    @Override
    public PageInfo query(TravelQueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(), queryObject.getPageSize(),queryObject.getOrderBy());
        List<Travel>list=travelMapper.selectForList(queryObject);
        return new PageInfo(list);
    }

    @Override
    public Travel selectByPrimaryKey(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public TravelContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void changeState(Travel travel) {
        //判断要更改的状态，如果是发布，需要更新发布时间
        if (Travel.STATE_RELEASE==travel.getState()) {
            travel.setReleaseTime(new Date());
        }
        travelMapper.updateState(travel);
    }


}
